<template>
    <el-form label-width="120px">

        <el-form-item label="横幅标题">

            <el-input v-model="info.title" placeholder="标题">

            </el-input>

        </el-form-item>

        <!--
        <el-form-item label="设为首页">

            <el-switch v-model="info.is_home" :active-value="1" :inactive-value="0"></el-switch>

        </el-form-item>
        -->
        <!-- <el-form-item label="所属平台">

            <el-select v-model="info.platform" placeholder="选择所属平台">
                <el-option v-for="item in platform_list" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
            </el-select>

        </el-form-item> -->
        <el-form-item label="状态">

            <el-switch v-model="info.status" :active-value="1" :inactive-value="0">

            </el-switch>

        </el-form-item>
    </el-form>

    <div class=" type-field flex gap-2">
        <el-tag  size="large" type="success" style="margin-right:10px;">
            <a class="item" @click="addBlock('image')">添加图片区域</a>
        </el-tag>
        <el-tag size="large" type="success" style="margin-right:10px;">
            <a class="item" @click="addBlock('text')">添加文字区域</a>
        </el-tag>
        <el-tag size="large" type="success" style="margin-right:10px;">
            <a class="item" @click="addBlock('html')">添加html代码区域</a>
        </el-tag>

        
    </div>    

    <grid-layout :layout.sync="block" :col-num="12" :row-height="30" :is-draggable="true" :is-resizable="true"
        :is-mirrored="false" :vertical-compact="true" :margin="[10, 10]" :use-css-transforms="true" class="layout-field">

        <grid-item @click="checkGridItem( item )" v-for="item in block" :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i" :key="item.i">
            <span class="remove" @click="removeItem( item.i )">x</span>
            <div class="grid-box" :class="'item-' + item.type + '-' +item.i">
            
                <template v-if="item.type == 'image'">
                    <img style="width:100%" :src=" VITE_URL + '/storage/' + item.content" alt="">
                </template>
                
                <template v-if="item.type == 'text'">

                    <div class="block-text" v-html="item.content"></div>
                </template>

            </div>            
           
        </grid-item>
    </grid-layout>


    <div class="panel-field">
    
        <div v-if="active_grid_item">
        
            <div v-if="active_grid_item.type == 'image' ">
            
                <ImageManager :maxNumber="1" v-model="active_grid_item.content"></ImageManager>
                
            </div>
            <div v-if="active_grid_item.type == 'text' ">
            
                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                :mode="'default'" />
                    <Editor style="width:100%; height: 500px; overflow-y: hidden;" v-model="active_grid_item.content"
                        :defaultConfig="editorConfig" :mode="'default'" @onCreated="handleCreated" />
                
            </div>
            <div v-if="active_grid_item.type == 'html' ">
                
                    
            </div>
        </div>
        
        
    </div>

    <div class=" table-below ">
        <a class="el-button el-button--primary" @click="saveDiy">保存</a>
    </div>
</template>

<script lang="ts" setup>

import { ref, reactive, shallowRef } from 'vue';
import { useRoute, useRouter } from "vue-router";
import axios from 'axios';
import ImageManager from '../../Common/image-manager.vue'
import { ElMessage } from 'element-plus';

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const VITE_URL = window.VITE_URL;

const route = useRoute();
const router = useRouter();
// const block = reactive([
const block = ref([
    // { "x": 0, "y": 0, "w": 2.5, "h": 2, "i": "0" },
    // { "x": 2, "y": 0, "w": 2, "h": 4, "i": "1" },
    // { "x": 4, "y": 0, "w": 2, "h": 5, "i": "2" },
    // { "x": 6, "y": 0, "w": 2, "h": 3, "i": "3" }
])
// const platform_list = ref([
//     {
//         label: '电脑端',
//         value: 'pc',
//     },
//     {
//         label: '小程序',
//         value: 'xcx',
//     }
// ])
const info = ref<object>({

    id: 0,
    title: '',
    is_home: 0,
    status: 1,
    platform: 'pc',
});

const init = () => {

    info.value.id = route.params.id ? route.params.id : 0;
    if( info.value.id ){
        const url: string = VITE_URL + '/admin.design.diy/single?id=' + info.value.id;
        axios.get(url).then((res: any) => {

            info.value = res.data

            block.value = res.data.diy;
        })
    }


}

const addBlock = ( type:any ) => {

    let newI = 0;
    console.log( block.value )
    block.value.forEach( ( item ) => {

        if( newI <= item.i ){

            newI  = item.i + 1;

        }

    } );

    let newBlk = {
                    x: 0, y: 0, w: 2, h: 3,
                    i: newI,
                    hover:0, 
                    type: type,
                    content:'',  // img类型: 为图片地址，text类型:文本内容，html类型:html代码
                    css_style:'',
                };

    block.value.push ( newBlk )

}

const removeItem =  ( val:number ) => {
    const index = block.value.map( item => item.i ).indexOf(val);
    block.value.splice(index, 1);
}

init();

const active_grid_item = ref( null );
const checkGridItem = ( grid:any ) => {

    active_grid_item.value = grid;

}

const saveDiy = () => {

    let url = VITE_URL + '/admin.design.diy/edit'
    if (info.value.id) {

        url += '?diy_id=' + info.value.id;
    }
    if (info.value.title.replace(/^(\s+)|(\s+)$/g, '').length == 0) {
        // alert('页面标题不能为空');
        ElMessage({
            message: '页面标题不能为空',
            type: 'error',
            duration: 800,
        })
        return;
    }

    for (var i = 0; i < block.value.length; i++) {



    }
    var data = {
        id          : info.value.id,
        title       : info.value.title,
        is_home     : info.value.is_home,
        status      : info.value.status,
        platform    : 'pc',
        diy: JSON.stringify(block.value),
    };
    
    axios.post(url, data).then(function (res) {

        ElMessage({
            message: !res.data.status?'保存成功':res.data.description,
            type: !res.data.status ? 'success' : 'error',
            duration: 800,
            onClose:()=>{
                if (!res.data.status) {
                    router.back();
                }
            }
        })
        

    });
    
}


const editorRef: any = shallowRef() // 编辑器实例， 下面 handleCreated 会给赋值
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    //     const allMenuKeys = editor.getAllMenuKeys()
    //     console.log( allMenuKeys )

}
const toolbarConfig: any = {}
const editorConfig: any = {
    placeholder: '请输入内容...',

    MENU_CONF: {
        uploadVideo: {
            server: VITE_URL + '/admin.FileUpload/wang_editor_upload',
            // form-data fieldName ，默认值 'wangeditor-uploaded-video'
            fieldName: 'file',

            // 单个文件的最大体积限制，默认为 10M
            maxFileSize: 5 * 1024 * 1024, // 5M

            // 最多可上传几个文件，默认为 5
            maxNumberOfFiles: 3,

            // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['video/*'],

            // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
            meta: {
                token: 'xxx',
                otherKey: 'yyy'
            },

            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            // headers: {
            //     Accept: 'text/x-json',
            //     otherKey: 'xxx'
            // },

            // 跨域是否传递 cookie ，默认为 false
            // withCredentials: true,

            // 超时时间，默认为 30 秒
            timeout: 15 * 1000, // 15 秒

            // 视频不支持 base64 格式插入
        },
        uploadImage: {
            server: VITE_URL + '/admin.FileUpload/wang_editor_upload',
            // form-data fieldName ，默认值 'wangeditor-uploaded-image'
            fieldName: 'file',

            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024, // 1M

            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,

            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],

            // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
            meta: {
                token: 'xxx',
                otherKey: 'yyy'
            },

            // 将 meta 拼接到 url 参数中，默认 false
            metaWithUrl: false,

            // 自定义增加 http  header
            // headers: {
            //     Accept: 'text/x-json',
            //     otherKey: 'xxx'
            // },

            // 跨域是否传递 cookie ，默认为 false
            // withCredentials: true,

            // 超时时间，默认为 10 秒
            timeout: 5 * 1000, // 5 秒
        }

    }
}
</script>

<style>
.vue-grid-item {
    display: flex;
    align-items: center;
    justify-content: center;
    border: solid #ccc 1px;
    background-color: #ccc;

    .remove{
        position: absolute;
        right: 3px;
        top: 0px;
    }
    .block-text{

        width:100%;
        height:100%;
    }
}

.type-field{

    a{
        cursor:pointer;
        

    }

}

.layout-field{
    background-color: #eee;
    /* max-width:1200px; */
    max-width:1440px;
    min-height:200px;
    margin-top:10px;

    .grid-box{

        width:100%;
        height: 100%;
        display: flex;
        align-items: flex-start;
        overflow: hidden;
    }

}

.pannel-field {

    


}

</style>